<?php 
define("BASEURL", "http://www.scoop.it");

class ScoopitAPI {

	private $oauth;
	private $SIHEADER = array('Accept-Encoding' => 'gzip,deflate');
	private $db;
	private $sharers;
	private $topics;
	
	function __construct($db, $options) {
		$this->db = $db;

			
		$accessToken = unserialize($db->getAccessToken());
		$this->oauth = new OAuth($options['scoopit_key'], $options['scoopit_secret']);
		$this->oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
		
		$this->sharers = $this->getSharers();
		$this->topics = $this->getTopics();
	}
	
	
	//Need 'sharerId' and 'cnxId'
	private function getSharers() {
		$this->oauth->fetch('http://www.scoop.it/api/1/profile',null,'GET', $this->SIHEADER);
		$response = json_decode($this->oauth->getLastResponse(), true);
		return $response['user']['sharers'];
	}
	
	//Need 'name' and 'id' from this array
	private function getTopics() {
		$this->oauth->fetch(BASEURL . '/api/1/profile', null, 'GET', $this->SIHEADER);
		$response = json_decode($this->oauth->getLastResponse(), TRUE);
		return $response['user']['curatedTopics'];
	}
	
	//Returns an array that contains share arrays
	private function createSharers($sharers, $shareText) {
		$arr = array();
		foreach ($sharers as &$v)
			array_push($arr, $this->createShare($v, $shareText));
		return $arr;
	}
	
	//Creates an array for each Share ie. facebook, twitter
	private function createShare($sharer, $shareText) {
		return array('sharerId' => $sharer, 'cnxId' => $this->findCNX($sharer), 'text' => $shareText);
	}
	
	//Finds the 'cnxId' for a share
	private function findCNX($sharer) {
		foreach($this->sharers as &$v) {
			if (strcasecmp($v['sharerId'], $sharer) == 0)
				return (int)$v['cnxId'];
		}
	}
	
	public function metaboxMainContent() {
		?>
		<table border="0" cellpadding="5">
			<tr>
				<td colspan="<?php echo count($this->getSharers()); ?>">
				<select id="select_topic">
					<option name="topics" value="">-</option>
				<?php
				foreach($this->topics as &$v) {
					?>
					<option name="topics" value="<?php echo $v['id']; ?>"><?php echo $v['name']; ?></option>
					<?php
				}
				?>
				</select>
				</td>
			</tr>
			<tr>
			<?php
			foreach ($this->sharers as &$v) {
			?>
				<td align="center">
				<img src="<?php echo plugins_url('images/' . $v['sharerName'] . '.png', __FILE__); ?>"></a><br>
				<input type="checkbox" name="sharers" value="<?php echo $v['sharerId']; ?>" />
				</td>
			<?php }
			?>
			</tr>
		</table>
		<?php
	}
	
	public function publish($title, $content, $shareText) {
		$sharers = unserialize($this->db->getSharers());
		$topicid = (int)array_pop($sharers);
		$json = json_encode($this->createSharers($sharers, $shareText));
		
		$args = array('action'=>"create", 'title'=>$title, 'content'=> $content, 'topicId' => $topicid, 'shareOn' => $json);
    	$this->oauth->fetch(BASEURL . '/api/1/post',$args, 'POST', $this->SIHEADER);
	}
	
	
}

?>